<template>
  <div class="class-analysis">
    <div class="container">
      <div class="analysis-header">
        <h1>📊 班级学情分析</h1>
        <div class="class-selector">
          <label for="classSelect">选择班级：</label>
          <select id="classSelect" v-model="selectedClass" @change="loadAnalysis">
            <option v-for="i in 17" :key="i" :value="i">{{ i }}班</option>
          </select>
          <input 
            type="date" 
            v-model="selectedDate" 
            @change="loadAnalysis"
            class="date-input"
          >
        </div>
      </div>
      
      <div v-if="loading" class="loading">
        <p>正在加载分析数据...</p>
      </div>
      
      <div v-else-if="error" class="error">
        <p>{{ error }}</p>
        <button @click="loadAnalysis" class="btn">重新加载</button>
      </div>
      
      <div v-else-if="analysis" class="analysis-content">
        <!-- 基本统计 -->
        <div class="stats-overview">
          <div class="stat-card">
            <div class="stat-icon">👥</div>
            <div class="stat-info">
              <div class="stat-number">{{ analysis.total_students }}</div>
              <div class="stat-label">参与学生</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">📈</div>
            <div class="stat-info">
              <div class="stat-number">{{ analysis.average_score }}</div>
              <div class="stat-label">平均分</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">⭐</div>
            <div class="stat-info">
              <div class="stat-number">{{ excellentRate }}%</div>
              <div class="stat-label">优秀率</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">✅</div>
            <div class="stat-info">
              <div class="stat-number">{{ passRate }}%</div>
              <div class="stat-label">及格率</div>
            </div>
          </div>
        </div>
        
        <!-- 分数分布图表 -->
        <div class="chart-section">
          <h3>📊 分数分布</h3>
          <div class="chart-container">
            <canvas ref="scoreChart" width="400" height="200"></canvas>
          </div>
        </div>
        
        <!-- 知识点分析 -->
        <div class="knowledge-analysis">
          <h3>🎯 知识点掌握情况</h3>
          <div class="knowledge-grid">
            <div 
              v-for="kp in analysis.knowledge_point_analysis" 
              :key="kp.knowledge_point"
              class="knowledge-card"
              :class="getKnowledgeCardClass(kp.accuracy_rate)"
            >
              <div class="knowledge-header">
                <h4>{{ kp.knowledge_point }}</h4>
                <span class="accuracy-badge" :class="getAccuracyClass(kp.accuracy_rate)">
                  {{ kp.accuracy_rate }}%
                </span>
              </div>
              <div class="knowledge-stats">
                <div class="stat-row">
                  <span>总题数：{{ kp.total_questions }}</span>
                  <span>正确：{{ kp.correct_count }}</span>
                  <span>错误：{{ kp.incorrect_count }}</span>
                </div>
                <div v-if="kp.common_wrong_answers.length > 0" class="wrong-answers">
                  <strong>常见错误选项：</strong>
                  <span v-for="(answer, index) in kp.common_wrong_answers" :key="index" class="wrong-option">
                    {{ answer }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 学生表现 -->
        <div class="student-performance">
          <div class="performance-section">
            <h3>🏆 优秀学生</h3>
            <div v-if="analysis.top_performers.length > 0" class="student-list">
              <div 
                v-for="(student, index) in analysis.top_performers" 
                :key="student.student_name"
                class="student-card top-performer"
              >
                <div class="student-rank">{{ index + 1 }}</div>
                <div class="student-info">
                  <div class="student-name">{{ student.student_name }}</div>
                  <div class="student-stats">
                    <span class="score">{{ student.score }}分</span>
                    <span class="accuracy">正确率: {{ student.accuracy_rate }}%</span>
                    <span class="time">{{ student.submission_time }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="no-data">暂无数据</div>
          </div>
          
          <div class="performance-section">
            <h3>🆘 需要帮助的学生</h3>
            <div v-if="analysis.need_help_students.length > 0" class="student-list">
              <div 
                v-for="student in analysis.need_help_students" 
                :key="student.student_name"
                class="student-card need-help"
              >
                <div class="student-info">
                  <div class="student-name">{{ student.student_name }}</div>
                  <div class="student-stats">
                    <span class="score">{{ student.score }}分</span>
                    <span class="accuracy">正确率: {{ student.accuracy_rate }}%</span>
                  </div>
                  <div v-if="student.weak_knowledge_points.length > 0" class="weak-points">
                    <strong>薄弱知识点：</strong>
                    <span v-for="point in student.weak_knowledge_points" :key="point" class="weak-point">
                      {{ point }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="no-data">暂无数据</div>
          </div>
        </div>
        
        <!-- 改进建议 -->
        <div v-if="analysis.common_mistakes.length > 0" class="suggestions">
          <h3>💡 教学建议</h3>
          <div class="suggestion-card">
            <h4>需要重点关注的知识点：</h4>
            <ul>
              <li v-for="mistake in analysis.common_mistakes" :key="mistake">
                {{ mistake }} - 建议加强练习和讲解
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Chart, registerables } from 'chart.js'
import axios from 'axios'

// 注册Chart.js组件
Chart.register(...registerables)

export default {
  name: 'ClassAnalysis',
  data() {
    return {
      selectedClass: 1,
      selectedDate: new Date().toISOString().split('T')[0],
      analysis: null,
      loading: false,
      error: null,
      scoreChart: null
    }
  },
  computed: {
    excellentRate() {
      if (!this.analysis || !this.analysis.score_distribution) return 0
      const excellent = this.analysis.score_distribution['90-100'] || 0
      return Math.round((excellent / this.analysis.total_students) * 100)
    },
    passRate() {
      if (!this.analysis || !this.analysis.score_distribution) return 0
      const pass = (this.analysis.score_distribution['90-100'] || 0) +
                   (this.analysis.score_distribution['80-89'] || 0) +
                   (this.analysis.score_distribution['70-79'] || 0) +
                   (this.analysis.score_distribution['60-69'] || 0)
      return Math.round((pass / this.analysis.total_students) * 100)
    }
  },
  mounted() {
    this.loadAnalysis()
  },
  methods: {
    async loadAnalysis() {
      this.loading = true
      this.error = null
      
      try {
        const params = {
          date: this.selectedDate
        }
        
        const response = await axios.get(`/api/class-analysis/${this.selectedClass}`, { params })
        this.analysis = response.data
        
        // 等待DOM更新后初始化图表
        this.$nextTick(() => {
          this.initScoreChart()
        })
        
      } catch (error) {
        console.error('加载分析数据失败:', error)
        this.error = '加载分析数据失败，请重试'
      } finally {
        this.loading = false
      }
    },
    
    initScoreChart() {
      if (!this.analysis || !this.$refs.scoreChart) return
      
      const ctx = this.$refs.scoreChart.getContext('2d')
      
      if (this.scoreChart) {
        this.scoreChart.destroy()
      }
      
      const distribution = this.analysis.score_distribution
      const labels = Object.keys(distribution)
      const data = Object.values(distribution)
      
      this.scoreChart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [{
            label: '学生人数',
            data: data,
            backgroundColor: [
              '#28a745', // 90-100
              '#17a2b8', // 80-89
              '#ffc107', // 70-79
              '#fd7e14', // 60-69
              '#dc3545'  // 0-59
            ],
            borderColor: [
              '#1e7e34',
              '#138496',
              '#e0a800',
              '#e8590c',
              '#c82333'
            ],
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            y: {
              beginAtZero: true,
              ticks: {
                stepSize: 1
              }
            }
          },
          plugins: {
            legend: {
              display: false
            },
            tooltip: {
              callbacks: {
                label: function(context) {
                  return `${context.parsed.y}人`
                }
              }
            }
          }
        }
      })
    },
    
    getKnowledgeCardClass(accuracy) {
      if (accuracy >= 80) return 'excellent'
      if (accuracy >= 60) return 'good'
      return 'need-improvement'
    },
    
    getAccuracyClass(accuracy) {
      if (accuracy >= 80) return 'high'
      if (accuracy >= 60) return 'medium'
      return 'low'
    }
  },
  
  beforeDestroy() {
    if (this.scoreChart) {
      this.scoreChart.destroy()
    }
  }
}
</script>

<style scoped>
.class-analysis {
  min-height: 100vh;
  padding: 20px;
  background-color: #f8f9fa;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

.analysis-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.analysis-header h1 {
  color: #333;
  margin: 0;
}

.class-selector {
  display: flex;
  align-items: center;
  gap: 10px;
}

.class-selector label {
  font-weight: bold;
  color: #666;
}

.class-selector select,
.date-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}

.loading, .error {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  font-size: 2em;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border-radius: 50%;
}

.stat-number {
  font-size: 2em;
  font-weight: bold;
  color: #333;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.chart-section {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  margin-bottom: 30px;
}

.chart-section h3 {
  margin-top: 0;
  color: #333;
}

.chart-container {
  height: 300px;
  position: relative;
}

.knowledge-analysis {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  margin-bottom: 30px;
}

.knowledge-analysis h3 {
  margin-top: 0;
  color: #333;
}

.knowledge-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.knowledge-card {
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid;
}

.knowledge-card.excellent {
  background: #d4edda;
  border-left-color: #28a745;
}

.knowledge-card.good {
  background: #d1ecf1;
  border-left-color: #17a2b8;
}

.knowledge-card.need-improvement {
  background: #f8d7da;
  border-left-color: #dc3545;
}

.knowledge-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.knowledge-header h4 {
  margin: 0;
  color: #333;
}

.accuracy-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.accuracy-badge.high {
  background: #28a745;
  color: white;
}

.accuracy-badge.medium {
  background: #ffc107;
  color: #333;
}

.accuracy-badge.low {
  background: #dc3545;
  color: white;
}

.knowledge-stats {
  font-size: 14px;
}

.stat-row {
  display: flex;
  gap: 15px;
  margin-bottom: 8px;
}

.wrong-answers {
  margin-top: 8px;
}

.wrong-option {
  display: inline-block;
  background: #f8f9fa;
  padding: 2px 6px;
  border-radius: 4px;
  margin: 2px;
  font-size: 12px;
}

.student-performance {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.performance-section {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.performance-section h3 {
  margin-top: 0;
  color: #333;
}

.student-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.student-card {
  padding: 15px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.student-card.top-performer {
  background: #d4edda;
  border-left: 4px solid #28a745;
}

.student-card.need-help {
  background: #fff3cd;
  border-left: 4px solid #ffc107;
}

.student-rank {
  width: 30px;
  height: 30px;
  background: #28a745;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.student-info {
  flex: 1;
}

.student-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.student-stats {
  display: flex;
  gap: 15px;
  font-size: 14px;
  color: #666;
}

.score {
  font-weight: bold;
  color: #333;
}

.weak-points {
  margin-top: 8px;
  font-size: 12px;
}

.weak-point {
  display: inline-block;
  background: #f8d7da;
  padding: 2px 6px;
  border-radius: 4px;
  margin: 2px;
}

.suggestions {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.suggestions h3 {
  margin-top: 0;
  color: #333;
}

.suggestion-card {
  background: #e8f4fd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #007bff;
}

.suggestion-card h4 {
  margin-top: 0;
  color: #333;
}

.suggestion-card ul {
  margin: 10px 0 0 0;
  padding-left: 20px;
}

.suggestion-card li {
  margin-bottom: 5px;
  color: #666;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 20px;
  font-style: italic;
}

.btn {
  background: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
}

.btn:hover {
  background: #0056b3;
}

@media (max-width: 768px) {
  .analysis-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .class-selector {
    flex-direction: column;
    width: 100%;
  }
  
  .stats-overview {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .student-performance {
    grid-template-columns: 1fr;
  }
  
  .knowledge-grid {
    grid-template-columns: 1fr;
  }
}
</style>